/**
 * 给树形结构属性重命名，并给节点添加索引index，删除无数据的children
 * @param {\} treeData 
 * @param {*} oldName 
 * @param {*} newName 
 * @returns 
 */
export function renameField(treeData, oldName, newName) {
    // 递归函数用于重命名字段
    function renameFieldRecursive(nodes) {
        nodes.forEach(function(node, index) {
            node.index = index
            node.isCheck = true
            node.selected = true
            if (node[oldName] !== undefined) {
                node[newName] = node[oldName]
                delete node[oldName]
            }
            if (node.children && node.children.length > 0) {
                renameFieldRecursive(node.children)
            }
            // 如果children 中无数据则删除该属性
            if (node.children && !node.children.length) {
                delete node.children
            }
        })
    }

    // 开始重命名
    renameFieldRecursive(treeData)
    return treeData
}

/** 
* 根据key寻找路径
*/
export function getPathByKey(curKey, data, key) {
    let result = [] // 记录路径结果
    const traverse = (curKey, path, data) => {
        if (data.length === 0) {
            return
        }
        for (const item of data) {
            path.push(item)
            if (item[key] === curKey) {
                result = JSON.parse(JSON.stringify(path))
                return
            }
            const children = Array.isArray(item.children) ? item.children : []
            traverse(curKey, path, children) // 遍历
            path.pop() // 回溯
        }
    }
    traverse(curKey, [], data)
    return result
}

export function revalueField(treeData, keyList) {
    // 递归函数用于重命名字段
    function revalueFieldRecursive(nodes) {
        nodes.forEach(function(node, index) {
            keyList.forEach(key => {
                if (!Number(node[key])) {
                    node[key] = 0
                } else {
                    node[key] = Number(node[key])
                }
            })
            if (node.childrenList && node.childrenList.length > 0) {
                revalueFieldRecursive(node.childrenList)
            }
        })
    }

    // 开始重命名
    revalueFieldRecursive(treeData)
    return treeData
}
